#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define N 32
int A[N],B[N],C[N];
int ma=0;
void* myfun(void *arg)
{
	int i;
	for(i=0 ;i<N;i++){
		C[i]+=A[i]*B[i];
	}
}
pthread_mutex_t mutexa;
void* myfun2(void *arg)
{
	int item;
	while(1){
		pthread_mutex_lock(&mutexa);
		item=ma;
		if(item>=N){
			pthread_mutex_unlock(&mutexa);
			break;
		}
		C[item]+=A[item]*B[item];
		printf("%d %d :%d\n",item,C[item],pthread_self());
		ma++;
		pthread_mutex_unlock(&mutexa);
	}
}

void* myfun3(void *arg)
{
	int i;
	for( ;ma<N;){
		i=ma;
		pthread_mutex_lock(&mutexa);
		C[i]+=A[i]*B[i];
		ma++;
		pthread_mutex_unlock(&mutexa);
	}
}

int main()
{
	int i;
	for(i=0;i<N;i++){
		A[i]=i;
		B[i]=-i;
		C[i]=0;
	}

	for(i=0;i<N;i++){
		printf("%d ", C[i]);
	}
		printf("\n");
	pthread_mutex_init(&mutexa,NULL);
	pthread_t id1,id2;
	pthread_create(&id1,NULL,myfun3,NULL);
	pthread_create(&id2,NULL,myfun3,NULL);
	pthread_join(id1,NULL);
	pthread_join(id2,NULL);

	//show result
/*	for(i=0;i<N;i++){
		printf("%d ", A[i]);
	}
		printf("\n");
	for(i=0;i<N;i++){
		printf("%d ", B[i]);
	}
		printf("\n");
*/
	for(i=0;i<N;i++){
		printf("%d ", C[i]);
	}
		printf("\n");
	exit(0);
}
